package com.onetech.adrewards.free.dialogs;

import java.util.List;

import android.app.Activity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.text.Html;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.analytics.tracking.android.Tracker;
import com.onetech.adrewards.free.R;
import com.onetech.adrewards.free.models.CommonModel;
import com.onetech.adrewards.free.objects.MailDomainDTO;
import com.onetech.adrewards.free.objects.RegisterSuccessDTO;
import com.onetech.adrewards.free.objects.ResultDTO;
import com.onetech.adrewards.free.objects.UserInfoDTO;
import com.onetech.adrewards.free.utils.AdrewadsUtils;
import com.todddavies.components.progressbar.ProgressWheel;
import com.zuzu.dialogs.BaseDialog;

public class RegisterEmailDialog extends BaseDialog {
	private UserInfoDTO mData=null;
	private MailDomainDTO mMailDomainData=null;
	private TextView mMessage=null;
	
	private TextView mNote=null;
	
	private EditText mEmail=null;
	private List<String> mDomains = null;
	private View mMainView=null;
	
	
	private Spinner mMailDomain = null;

	
	
	private View mSendMailBtn=null;
	
	private ProgressWheel mProgressBar=null;
	
	private long mCurrentTime = 0;
	private boolean isSending=false;
	
	private View mNotFoundData=null;
	private View mWaitingForLoading=null;
	protected View mBtnRetry=null;
	protected ProgressWheel mProgress=null;
	
	private SendMailInviteCodeDataTask mSendMail=null;
	
	
	RegisterSuccessDTO mResult=null;
	
	private int buttonPressId=-1; 
	
	
	private LoadMailDomainTask mLoadMailDomainTask=null;
	private Tracker mTracker;
	private Activity mActivity=null;
	
	
	public RegisterEmailDialog(Activity context,UserInfoDTO dataUser){
		super(context, context.getString(R.string.register_email_title),
				TYPE_NO_BUTTON, R.layout.dialog_register_email);
		mActivity=context;
		if(dataUser==null){
			dismiss();
		}
		//showMyPoints(false);
		initView();
		initListener();
		mData=dataUser;
		loadMailDomainData();

		
	}	
	private void initView() {
		mMessage=(TextView)findViewById(R.id.msg1);
		mNote=(TextView)findViewById(R.id.mailDomainNote);
	
		
		mEmail = (EditText)findViewById(R.id.email);
		mMailDomain =  (Spinner) findViewById(R.id.mailDomain);
		
		 
		
		mSendMailBtn=(LinearLayout)findViewById(R.id.btnSendMail);
		initNotFoundAndLoadingView();
		showNotFoundOrLoadingView(false, false);
		
		mMainView=(LinearLayout)findViewById(R.id.mainContainer);
		//showMainView(false);
		//showFooterView(false);
		
		mProgressBar=(ProgressWheel)findViewById(R.id.splashProgressBar);
		mProgressBar.setText("");
		mProgressBar.setContourColor(Color.TRANSPARENT);
		mProgressBar.spin();
		mProgressBar.setVisibility(View.INVISIBLE);
		
	}
	private void initListener() {
		mSendMailBtn.setOnClickListener(this);
		
	}
	
	protected void initNotFoundAndLoadingView(){
		mNotFoundData=(LinearLayout) findViewById(R.id.notFoundDataContainer);		
		mWaitingForLoading=(LinearLayout) findViewById(R.id.waitingLoading);
		mProgress=(ProgressWheel)findViewById(R.id.progressWheel);
		mProgress.spin();
		showNotFoundOrLoadingView(false, true);
		mBtnRetry=(LinearLayout)findViewById(R.id.btnRetry);
		
	}
	protected void showNotFoundOrLoadingView(boolean isShowNotFound,boolean isShowLoading){
		if(isShowNotFound){
			mNotFoundData.setVisibility(View.VISIBLE);
		}else{
			mNotFoundData.setVisibility(View.GONE);
		}
		if(isShowLoading){
			mWaitingForLoading.setVisibility(View.VISIBLE);
		}else{
			mWaitingForLoading.setVisibility(View.GONE);
		}
	}
	
	private void loadDomain()
	{
		ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(mActivity,android.R.layout.simple_spinner_item, mDomains);
		
        // Drop down layout style - list view with radio button
        spinnerAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 
        // attaching data adapter to spinner
        mMailDomain.setAdapter(spinnerAdapter);
	}
	private void loadMailDomainData(){
		if(mMailDomainData==null){
			if(mLoadMailDomainTask==null){
				mLoadMailDomainTask=new LoadMailDomainTask();
				mLoadMailDomainTask.execute();
			}
		}
	}
	private class LoadMailDomainTask extends AsyncTask<Void, Void, MailDomainDTO>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();	
			showNotFoundOrLoadingView(false, true);
			//showMainView(false);
		}
		@Override
		protected MailDomainDTO doInBackground(Void... params) {
			try {
				return CommonModel.getInstance().getMailDomain();
			} catch (Exception e) {
 				return null;
			}			
		}
		@Override
		protected void onPostExecute(MailDomainDTO result) {
			super.onPostExecute(result);
			try {
				if(result!=null){
					mMailDomainData=result;
					
					mMessage.setText(Html.fromHtml(mMailDomainData.msg));
					mNote.setText(Html.fromHtml(mMailDomainData.note));
					mDomains = mMailDomainData.mailDomain;
					loadDomain();
					
					showNotFoundOrLoadingView(false,false);
					//showMainView(true);
				}else{
					showNotFoundOrLoadingView(true, false);
					//showMainView(false);
				}
			} catch (Exception e) {
				showNotFoundOrLoadingView(true, false);
				//showMainView(false);
			}
		}
	}
	@Override
	public void onClick(View v) {
		int id = v.getId();
		if(id == R.id.btnSendMail)
		{
			
			String email = mEmail.getText().toString().trim();
			if(email.length()<1){
				AdrewadsUtils.showMessage(mActivity, mActivity.getString(R.string.login_invite_code_email_empty_warning));
				
				
				
				return;
			}
			buttonPressId=R.id.btnSendMail;
			if(isSending){
				return;
			}
			long mTime=System.currentTimeMillis();
			long time=(mTime-mCurrentTime)/1000;
			if(time > 3){
				mCurrentTime=mTime;
				sendMail();				
			}else{
				mCurrentTime=mTime;
				Toast.makeText(mActivity, mActivity.getString(R.string.login_invite_code_warning), Toast.LENGTH_LONG).show();
			}
		}
		else {
	
			super.onClick(v);
	
		}
	}
	private void sendMail(){
		if(mSendMail==null || mSendMail.getStatus()==Status.FINISHED){
			mSendMail =new SendMailInviteCodeDataTask();
			mSendMail.execute();
		}
	}
	
	private class SendMailInviteCodeDataTask extends AsyncTask<Void, Void, ResultDTO>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			isSending=true;
			mProgressBar.setVisibility(View.VISIBLE);
		}
		@Override
		protected ResultDTO doInBackground(Void... params) {
			try {				
				
				String email =  mEmail.getText().toString().trim() + String.valueOf(mMailDomain.getSelectedItem());
				
				return CommonModel.getInstance().registerEmail(email);
				
			} catch (Exception e) {
				return null;
			}			
		}
		@Override
		protected void onPostExecute(ResultDTO result) {
			super.onPostExecute(result);
			try {
				if(result!=null){
					
					if(buttonPressId==R.id.btnSendMail){
						if(!"0".equals(result.getError_code())){
							AdrewadsUtils.showMessage(mActivity, result.getError_message());
							return;
						}else{
							if(result.getSuccessMessage()!=null && result.getSuccessMessage().trim().length()>0){
								SuccessDialog mDialog=new SuccessDialog(mActivity,  mActivity.getString(R.string.sendmailcompleted), result.getSuccessMessage(), "");
								mDialog.show();
								dismiss();
							}else { 
								//
							}
						}
					}else{
						//
					}
				}else{
					AdrewadsUtils.showInfoDialog(mActivity, mActivity.getString(R.string.error_message_title), mActivity.getString(R.string.server_error_message));
				}
			} catch (Exception e) {
				AdrewadsUtils.showInfoDialog(mActivity, mActivity.getString(R.string.error_message_title), mActivity.getString(R.string.server_error_message));
			}
			finally{
				mProgressBar.setVisibility(View.INVISIBLE);
				isSending=false;
			}
		}
	}
	
	
	
	@Override
    public void onStart() {
        super.onStart();
        try {
            mTracker.set(Fields.SCREEN_NAME, mActivity.getString(R.string.ListGiftCardFragment));            
            mTracker.send(MapBuilder.createAppView().build());            
		} catch (Exception e) {
		}
    }
}
